<?php

/**
 * Implements a menu
 * @author Pablo
 * @since 1.0
 */
class BlgMenu{
	protected $root;
	
	protected $section_class;
	protected $item_class;	

	function __construct(BlgMenuItem $root= NULL, $section_class='menu_section', $item_class='menu_item'){
		if(!$this->set_root($root)){
			$this->root= new BlgMenuItem(array(
				'name' => 'site',
				'href' => blg_get_site_url(),
				'text' => blg_get_config('site_title'),
				'priority' => '10',		
				'is_action' => FALSE,
				'selected' => TRUE,
				'enabled' => TRUE,
				'visible' => TRUE,
				'parent' => NULL				
			));	
		}
		
		$this->set_class($section_class, $item_class);
	}

	/**** SETTERS && GETTERS ****/
	
	public function set_root($root){
		if($root instanceof BlgMenuItem && !empty($root)){
			$this->root= $root;
			return TRUE;
		}
		return FALSE;
	}
	
	public function get_root(){
		return $this->root;
	}
	
	public function set_class($section_class= NULL, $item_class= NULL){
		if(isset($section_class))
			$this->section_class= $section_class;
			
		if(isset($item_class))
			$this->item_class= $item_class;
	}	
	
	/****** CLASS ******/
	
	/* 
	 * Posible CLASSES FOR ITEMS:
	 * [class_name]
	 * [class_name]_disabled 
	 * [class_name]_selected
	 * [class_name]_disabled_selected
	 */	
	
	protected function build_item_class($item){
		$class= $this->item_class.($item->enabled?'':'_disabled');
		$class= ($item->selected?$class.'_selected':$class);

		return $class;
	}
	
	/****** SITEMAP ******/
	
	protected function print_site_map_item(BlgMenuItem $item, $print_disabled_items= true){
		if(!empty($item->href) && $item->enabled){
			$text= '<a '.(!empty($item->target)?'target="'.$item->target.'" ':'').'href="'.$item->href.'">'.$item->text.'</a>';
		}else{
			$text= '<span>'.$item->text.'</span>';
		}
		
		$html= '<li class="'.($this->build_item_class($item)).'">'.$text.'</li>'."\n";
		
		if( $item->has_children() && ($item->enabled || (!$item->enabled && $print_disabled_items)) ){
			$html.= '<ul class="'.$this->section_class.'">'."\n";
						
			foreach($item->get_children() as $i => $child){
				$html.= $this->print_site_map_item($child, $print_disabled_items);
			}
			
			$html.= '</ul>'."\n";
		}
		
		return $html;		
	}
	
	public function print_site_map($print_disabled_items= true){		
		$html = '<ul class="'.$this->section_class.'">'."\n";		
		$html.= $this->print_site_map_item($this->root, $print_disabled_items);				
		$html.= '</ul>'."\n";
		
		return $html;
	}	
	
	/****** MENU ******/
	
	
}